<template>
  <el-scrollbar wrap-class="scrollbar-wrapper" v-loading="loading">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-position="left"
      status-icon
    >
      <!-- 授信申请 -->
      <div class="header">
        <div class="title">授信申请</div>
        <div v-if="status !== null" class="mt-lg">
          <el-alert
            v-show="status === 4"
            class="mb-lg"
            title="恭喜您通过银行授信申请！"
            type="success"
            show-icon
          />
          <el-alert
            v-show="[1, 2, 3].includes(status)"
            class="mb-lg"
            title="平台审核中，请耐心等待。"
            type="warning"
            show-icon
          />
          <el-alert
            v-show="status === 0"
            class="mb-lg"
            :title="`审核未通过，驳回原因：${details.remarks}`"
            type="error"
            show-icon
          />
        </div>
        <el-row :gutter="24" class="pb-lg pl-lg lr-lg">
          <el-col :span="8">
            <el-form-item label-position="top" label="授信银行：" class="wh">
              <span>{{ details.bank }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="授信有效期：" class="wh">
              <span v-if="details.timeExpiry && details.timeValid">
                {{ filters.dateYMDHMSFormat(details.timeValid) }} -
                {{ filters.dateYMDHMSFormat(details.timeExpiry) }}
              </span>
              <span v-else>-</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="授信利率：" class="wh">
              <span v-if="details.rate"> {{ details.rate || "0" }} %</span>
              <span v-else> - </span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="银行授信额度：" class="wh">
              <span v-if="details.bankAmount">
                {{ details.bankAmount }}万元</span
              >
              <span v-else> - </span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="平台授信额度：" class="wh">
              <span v-if="details.amount"> {{ details.amount }} 万元</span>
              <span v-else> - </span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="剩余授信额度：" class="wh">
              <span v-if="details.currentAmount">
                {{ details.currentAmount }}万元</span
              >
              <span v-else> - </span>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="list-body">
        <c-main-template
          class="mt-lg"
          minHeight="auto"
          :title="item.name"
          :isBreadcrumb="false"
          v-for="(item, index) in list"
          :key="index"
        >
          <el-row :gutter="24" class="pd-24">
            <el-col :span="d.row" v-for="(d, j) in item.list" :key="j">
              <!-- 输入框 -->
              <el-form-item
                :class="!d.disabled ? 'el-form--label-top' : ''"
                v-if="d.type === 'text'"
                :label="`${d.name}：`"
                :prop="d.key"
              >
                <el-input
                  v-if="!d.disabled"
                  v-model="ruleForm[d.key]"
                  :placeholder="`请输入${d.name}`"
                  @blur="onDraftSave"
                  size="large"
                />
                <span v-else>{{ ruleForm[d.key] }}</span>
              </el-form-item>
              <!-- 文本输入框 -->
              <el-form-item
                :class="!d.disabled ? 'el-form--label-top' : ''"
                v-else-if="d.type === 'textarea'"
                :label="`${d.name}：`"
                :prop="d.key"
              >
                <el-input
                  v-if="!d.disabled"
                  v-model="ruleForm[d.key]"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  type="textarea"
                  size="large"
                  :placeholder="`请输入${d.name}`"
                  @blur="onDraftSave"
                />
                <span v-else>{{ ruleForm[d.key] }}</span>
              </el-form-item>
              <!-- 日期 -->
              <el-form-item
                :class="!d.disabled ? 'el-form--label-top' : ''"
                v-else-if="d.type === 'time'"
                :label="`${d.name}：`"
                :prop="d.key"
              >
                <el-date-picker
                  v-if="!d.disabled"
                  type="date"
                  class="wh"
                  size="large"
                  v-model="ruleForm[d.key]"
                  :placeholder="`请输入${d.name}`"
                  @blur="onDraftSave"
                >
                </el-date-picker>
                <span v-else>{{
                  filters.dateYMDHMSFormat(ruleForm[d.key])
                }}</span>
              </el-form-item>
              <!-- 中征码 -->
              <el-form-item
                :class="!d.disabled ? 'el-form--label-top' : ''"
                v-else-if="d.type === 'code'"
                :label="`${d.name}：`"
                :prop="d.key"
              >
                <c-code
                  @update:modelValue="onDraftSave"
                  :config="d"
                  v-model="ruleForm[d.key]"
                />
              </el-form-item>
              <!-- 选择文件 -->
              <el-form-item
                class="el-form--label-top"
                v-else-if="d.type === 'file'"
                :label="`${d.name}`"
                label-position="top"
                :prop="d.key"
              >
                <c-file-upload
                  :disabled="d.disabled"
                  :tips="d.describe"
                  v-model="ruleForm[d.key]"
                  @update:modelValue="onDraftSave"
                />
              </el-form-item>
              <!-- 证件 -->
              <el-form-item
                class="el-form--label-top"
                v-else-if="d.type === 'card'"
                :label="`${d.name}`"
                :prop="d.key"
              >
                <c-file-upload
                  :disabled="d.disabled"
                  :tips="d.describe"
                  v-model="ruleForm[d.key]"
                  @update:modelValue="onDraftSave"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </c-main-template>
      </div>
    </el-form>
  </el-scrollbar>
  <div class="footer" v-if="(status === null || status === 0) && !isView">
    <div class="mr-lg">
      <el-button :loading="buttonLoading" type="primary" @click="handleSubmit">
        {{ status === 0 ? "重新申请" : "提交申请" }}
      </el-button>
    </div>
    <div class="flex-y-center">
      <div class="el-checkbox" @click="handleOpenManual">
        <div
          :class="ruleForm.manual ? 'is-checked' : ''"
          class="el-checkbox__input"
        >
          <div class="el-checkbox__inner"></div>
        </div>
        <div class="el-checkbox__label">同意《银行授信协议》</div>
      </div>
      <div class="save-time" v-if="time">已保存 {{ time }}</div>
    </div>
  </div>
  <c-agreement ref="cAgreementRef" @change="ruleForm.manual = true" />
</template>
<script setup>
import { ref, onMounted, getCurrentInstance } from "vue";
import cCode from "./components/Code.vue";
import cAgreement from "./components/Agreement.vue";
import cFileUpload from "@/components/Upload/FileUpload.vue";
import { useRoute, useRouter } from "vue-router";
import { deepClone, currentTime } from "@/utils/index.js";
import { ElMessage } from "element-plus";
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
const ruleForm = ref({});
const ruleFormRef = ref();
const cAgreementRef = ref();
const rules = ref({});
const list = ref([]);
const details = ref({});
const status = ref(null);
const time = ref(null);
const loading = ref(false);
const buttonLoading = ref(false);
// 是否是详情查看
const isView = ref(false);
// 银行信息
onMounted(() => {
  getById();
});
const getById = () => {
  const query = route.query;
  loading.value = true;
  if (query.isView) {
    isView.value = true;
  }
  if (query.creditId) {
    // 已授信
    proxy
      .$get({
        url: "/sellerCreditAmountApply/getDetails",
        params: { id: query.creditId },
      })
      .then((res) => {
        details.value = res.creditAmountApply;
        status.value = res.creditAmountApply.status;
        if (res.creditTemplate) {
          list.value = getList(res.creditTemplate.list || []);
          ruleForm.value = JSON.parse(res.creditTemplate.form);
        }
        rules.value = getRulesList();
        loading.value = false;
      });
  } else if (query.bankId && !query.status) {
    // 未授信
    details.value.bankId = query.bankId;
    details.value.bank = query.bankName;
    proxy
      .$get({
        url: "/sellerCreditAmountApply/getTemplate",
        params: { bankId: query.bankId },
      })
      .then((res) => {
        list.value = getList(res);
        rules.value = getRulesList();
        getDraftInfo();
        loading.value = false;
      });
  }
};

const handleOpenManual = () => {
  cAgreementRef.value.handleOpen();
};
const getList = (res) => {
  // 状态(0-待补充资料,1-待平台审核,2-待银行审核,3-待平台确认授信金额,4-已完成)
  const data = JSON.parse(res);
  return (data || []).map((x) => {
    x.list = x.list.map((r) => {
      if (isView.value) {
        r.disabled = true;
      } else if ([1, 2, 3, 4].includes(status.value)) {
        r.disabled = true;
      } else if (status.value === null) {
        r.disabled = false;
      }
      return r;
    });
    return x;
  });
};
const handleSubmit = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      if (!ruleForm.value.manual) {
        ElMessage.warning("请阅读并同意《银行授信协议》！");
        return;
      }
      buttonLoading.value = true;
      const data = {
        bankId: details.value.bankId,
        form: JSON.stringify(ruleForm.value),
      };
      let url = "/sellerCreditAmountApply/applyCredit";
      if (route.query.creditId) {
        url = "/sellerCreditAmountApply/userReplenish";
        data.id = route.query.creditId;
      }
      proxy.$post({ url, data }).then(
        (res) => {
          ElMessage.success("操作成功！");
          buttonLoading.value = false;
          router.go(-1);
        },
        () => {
          buttonLoading.value = false;
        }
      );
    }
  });
};
const getDraftInfo = () => {
  const data = {
    business: 1,
    innerNo: details.value.bankId,
  };
  proxy.$post({ url: "/draft/get", data }).then((draft) => {
    // 有草稿拿草稿 没有取企业认证
    if (draft) {
      ruleForm.value = JSON.parse(draft).data;
      time.value = draft.time;
    } else {
      proxy.$get({ url: "/seller/detail" }).then((user) => {
        user.sellerInfo.email = user.email;
        user.sellerInfo.authStatus = user.authStatus;
        ruleForm.value = user.sellerInfo;
      });
    }
  });
};
const onDraftSave = () => {
  const data = {
    business: 1,
    data: JSON.stringify(ruleForm.value),
    innerNo: details.value.bankId,
  };
  proxy.$post({ url: "/draft/save", data }).then((res) => {
    time.value = currentTime();
  });
};
const getRulesList = () => {
  const r = {};
  for (let i = 0; i < list.value.length; i++) {
    const innerList = list.value[i].list;
    for (let j = 0; j < innerList.length; j++) {
      const { required, key, name, type } = innerList[j];
      if (required) {
        r[key] = {
          text: [
            {
              required: true,
              message: `请输入${name}`,
              trigger: "blur",
            },
          ],
          textarea: [
            {
              required: true,
              message: `请输入${name}`,
              trigger: "blur",
            },
          ],
          time: [
            {
              required: true,
              message: `请选择${name}`,
              trigger: "change",
            },
          ],
          file: [
            {
              type: "array",
              required: true,
              message: `请选择${name}`,
              trigger: "change",
            },
          ],
          code: [
            {
              validator: (rule, value, callback) => {
                if (!value) {
                  callback(new Error(`请选择${name}`));
                } else if (value && !value.code) {
                  callback(new Error(`请输入内容`));
                } else {
                  callback();
                }
              },
              trigger: "change",
            },
          ],
        }[type];
      }
    }
  }
  return r;
};
</script>

<style lang="less" scoped>
:deep(.el-form-item.el-form--label-top) {
  display: block;
}
.save-time {
  font-size: 12px;
  color: #9a9a9a;
}
.list-body {
  margin-left: 24px;
  margin-right: 24px;
  margin-bottom: 70px;
}
.footer {
  position: absolute;
  bottom: 0px;
  background: #fff;
  height: 64px;
  width: calc(100vw - 176px - 3rem);
  display: flex;
  align-items: center;
  padding-left: 48px;
}
.header {
  background: #ffffff;
  padding-top: 24px;
  padding-left: 24px;
  .title {
    font-size: 16px;
    font-weight: 500;
    color: #202020;
  }
}
</style>